<?php

namespace App\Http\Controllers\AgentAdmin;

use App\Http\Controllers\Controller;
use App\Models\AgentUser;
use App\Models\Notice;
use App\Services\ObsService;
use Illuminate\Support\Arr;

class NoticeController extends Controller
{
    /** @var ObsService */
    private $obsService;

    /**
     * BannerController constructor.
     */
    public function __construct(ObsService $obsService)
    {
        $this->obsService = $obsService;
    }

    /** 上传公告封面图图片 */
    public function uploadImage()
    {
        $key = 'notice_cover_image/' . uniqid();
        $file = request()->file('file');
        $imageUrl = $this->obsService->upload($key, $file);

        return ['image_url' => $imageUrl];
    }

    public function index()
    {
        /** @var AgentUser $user */
        $user = auth()->user();

        $query = Notice::query()
            ->with(['to_user'])
            ->where('agent_id', $user->agent_id)
            ->when(request()->template_id, function ($q) {
                return $q->where('template_id', request()->template_id);
            })
            ->when(!request()->template_id, function ($q) {
                return $q->where('to_user_id', 0);
            })
            ->when(request()->keyword, function ($q) {
                return $q->where(function ($q1) {
                    $likeVal = '%' . request()->keyword . '%';

                    return $q1->whereHas('to_user', function ($q2) use ($likeVal) {
                        return $q2->where('mobile', 'like', $likeVal);
                    })->orWhere('content', 'like', $likeVal);
                });
            })
            ->orderByDesc('id');

        return paginate_result($query);
    }

    public function store()
    {
        /** @var AgentUser $user */
        $user = auth()->user();
        $params = request()->validate([
            'title' => 'required',
            'content' => 'required',
            'publish_time' => 'nullable',
            'cover_image_url' => 'nullable',
        ]);

        $params = Arr::add($params, 'publish_time', now());

        /** @var Notice $notice */
        $notice = get_entity(Notice::class);
        $notice->agent_id = $user->agent_id;
        $notice->fill($params);
        $notice->save();
    }

    public function destroy($id)
    {
        Notice::destroy($id);
    }
}
